package com.ibangnuo.manage.service.order;

import com.alibaba.fastjson.JSONObject;
import com.ibangnuo.framework.domain.SuccessionSettlement;
import com.ibangnuo.framework.domain.request.order.OrderQueryGroupRequest;
import com.ibangnuo.framework.domain.request.order.SuccessionSettlementQueryRequest;
import com.ibangnuo.framework.model.response.*;
import com.ibangnuo.framework.redisKey.Rediskey;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.OrderMapper;
import com.ibangnuo.manage.dao.SuccessionSettlementMapper;
import com.ibangnuo.manage.dao.SuccessionSettlementRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author: wwy
 * @Date: 2020-01-02 17:22
 */
@Service
public class SuccessionSettlementService {
    @Autowired
    private SuccessionSettlementRepository successionSettlementRepository;
    @Autowired
    private SuccessionSettlementMapper successionSettlementMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 分页条件查询
     * @param page
     * @param size
     * @param successionSettlementQueryRequest
     * @return
     */
    public QueryResponseResult findList(int page, int size, SuccessionSettlementQueryRequest successionSettlementQueryRequest) {
        if(successionSettlementQueryRequest == null){
            successionSettlementQueryRequest = new SuccessionSettlementQueryRequest();
        }
        SuccessionSettlementQueryRequest finalSuccessionSettlementQueryRequest = successionSettlementQueryRequest;
        Specification specification = (var1, var2, var3)->{
            Predicate predicate = var3.conjunction();
            if(StringUtils.isNotEmpty(finalSuccessionSettlementQueryRequest.getSn())){
                predicate.getExpressions().add(var3.equal(var1.get("sn"), finalSuccessionSettlementQueryRequest.getSn()));
            }
            if(finalSuccessionSettlementQueryRequest.getEndTime() != null && finalSuccessionSettlementQueryRequest.getStartTime() !=null){
                //起始日期
                predicate.getExpressions().add(var3.greaterThanOrEqualTo(var1.get("createTime").as(Date.class), finalSuccessionSettlementQueryRequest.getStartTime()));
                //结束日期
                predicate.getExpressions().add(var3.lessThanOrEqualTo(var1.get("createTime").as(Date.class), finalSuccessionSettlementQueryRequest.getEndTime()));
            }
            return predicate;
        };
        if(page <= 0){
            page = 1;
        }
        page = page - 1;
        if(size <= 0){
            size = 20;
        }
        Pageable pageable = PageRequest.of(page,size);
        Page all = successionSettlementRepository.findAll(specification, pageable);
        QueryResult queryResult = new QueryResult();
        queryResult.setList(all.getContent());
        queryResult.setTotal(all.getTotalElements());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 根据时间，sn号查询
     * 1.开始时间只能是上一次结算时间，
     * 2.结束时间为当前时间
     * 3.依据条件查询订单表，保存进入redis
     * @param successionSettlementQueryRequest
     * @return
     */
    public ObjectResult querySuccSet(SuccessionSettlementQueryRequest successionSettlementQueryRequest) {
        Long id = PrimaryKeyUtil.nextId();
        Date maxTime = successionSettlementMapper.findMaxTimeBySn(successionSettlementQueryRequest.getSn());

        Date endTime = new Date();
        if(maxTime == null){
            //第一次插入
            endTime = null;
        }
        OrderQueryGroupRequest orderQueryGroupRequest = new OrderQueryGroupRequest();
        orderQueryGroupRequest.setStartTime(maxTime);
        orderQueryGroupRequest.setEndTime(endTime);
        orderQueryGroupRequest.setSn(successionSettlementQueryRequest.getSn());
        orderQueryGroupRequest.setPayWay(0);//支付宝
        List<Map> aliList = orderMapper.queryGroup(orderQueryGroupRequest);
        orderQueryGroupRequest.setPayWay(1);//微信
        List<Map> wecharList = orderMapper.queryGroup(orderQueryGroupRequest);
        orderQueryGroupRequest.setPayWay(null);//微信
        List<Map> allList = orderMapper.queryGroup(orderQueryGroupRequest);
        Map<String,Object> map = new HashMap<>();
        map.put("aliList",aliList);
        map.put("wecharList",wecharList);
        map.put("allList",allList);
        map.put("id",id+"");
        map.put("startTime",maxTime);
        map.put("endTime",endTime);
        map.put("sn",successionSettlementQueryRequest.getSn());
        //放入缓存
        String mapJson = JSONObject.toJSONString(map);
        stringRedisTemplate.opsForValue().set(Rediskey.SUCC_SETT_ID+id,mapJson,30*60, TimeUnit.SECONDS);
        return new ObjectResult(CommonCode.SUCCESS,map);
    }

    /**
     * 添加
     * 1.从缓存中拿去
     * 2.不存在，进行报错处理
     * @param redisId
     * @return
     */
    public ResponseResult add(String redisId) {
        String key = Rediskey.SUCC_SETT_ID+redisId;
        String mapJsonStr = String.valueOf(stringRedisTemplate.opsForValue().get(key));
        Map map = JSONObject.parseObject(mapJsonStr, Map.class);
        SuccessionSettlement successionSettlement = new SuccessionSettlement();
        successionSettlement.setStartTime(new Date(Long.parseLong(String.valueOf(map.get("startTime")))));
        successionSettlement.setEndTime(new Date(Long.parseLong(String.valueOf(map.get("endTime")))));
        successionSettlement.setModel(mapJsonStr);
        successionSettlement.setCreateTime(new Date());
        successionSettlement.setSn(String.valueOf(map.get("sn")));
        successionSettlementRepository.save(successionSettlement);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    public ObjectResult findById(String id) {
        Optional<SuccessionSettlement> optional = successionSettlementRepository.findById(id);
        if(optional.isPresent()){
            SuccessionSettlement successionSettlement = optional.get();
            String model = successionSettlement.getModel();
            Map map = JSONObject.parseObject(model, Map.class);
            return new ObjectResult(CommonCode.SUCCESS,map);
        }
        return new ObjectResult(CommonCode.FAIL,null);
    }
}
